package edu.tjut.tjutcommunity.utils;

import com.aliyun.oss.OSS;
import edu.tjut.tjutcommunity.exception.PicNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Objects;
import java.util.UUID;

@Component
public class UploadUtils {
    @Value("${aliyun.bucket-name}")
    private String bucketName;
    @Value("${aliyun.endpoint}")
    private String endpoint;

    private static StringRedisTemplate stringRedisTemplate;

    @Autowired
    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        UploadUtils.stringRedisTemplate = redisTemplate;
    }

    public String uploadImage(OSS ossClient, MultipartFile file, String pathSuffix) {
        //上传的操作
        //将文件的名字编程唯一的再上传
        int i = Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf(".");//获取上传的文件的原名
        String suffix = file.getOriginalFilename().substring(i);
        //借助  UUID 将文件名编程唯一的 重新定义
        String uuid = UUID.randomUUID().toString();
        //定义上传oss的文件路径
        String filename = pathSuffix + "/" + uuid + suffix;
        // 上传文件到指定的存储空间（bucketName）并将其保存为指定的文件名称（objectName）。
        try {
            upload(ossClient, file.getInputStream(), filename);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return "https://" + bucketName + "." + endpoint + "/" + filename;
    }

    public void upload(OSS ossClient, InputStream ips, String filename) {
        ossClient.putObject(bucketName, filename, ips);
    }

    public static void SetPic(Object obj, String stuId, String concat, Integer length) throws InvocationTargetException, IllegalAccessException, ClassNotFoundException, NoSuchMethodException, PicNotFoundException {
        for (int i = 1; i <= length; i++) {
            Method method = obj.getClass().getMethod("setPic" + i, String.class);
            String query = stuId + concat + i;
            String url = stringRedisTemplate.opsForValue().get(query);
            if (url == null) throw new PicNotFoundException();
            method.invoke(obj, url);
        }
    }
}
